<template>
	<view class="container">
		<!-- 顶部渐变背景区域 -->
		<view class="header-section">
			<!-- 默写报告模块 -->
			<view class="report-header">
				<view class="report-left">
					<view class="report-title">作文批改报告</view>
					<view class="report-desc">1. 建议重点训练"是、做"等字。</view>
					<view class="report-desc">2. 重点关注"小明"的学习情况，他的错误较多</view>
				</view>
				<view class="report-right">
					<view class="task-detail f f-a-c f-j-c">任务详情
						<image src="/static/youjiantou.png" style="width: 30rpx;height: 30rpx;" mode=""></image>
					</view>
					<view class="ai-bg">
						<image src="/static/AI.png" class="ai-icon" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 数据统计模块 -->
		<view class="stats-section">
			<view class="stats-grid">
				<view class="stat-item">
					<text class="stat-label">人数:{{ reportData.students ? reportData.students.length : 0 }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">提交:{{ reportData.submitNum }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">AI批改:{{ reportData.checkNum }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">异常:{{ reportData.exceptNum }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">未审阅:</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">未提交:</text>
				</view>
			</view>

			<view class="summary-stats">
				<view class="summary-item">
					<text class="summary-number">{{ scoreStatistics.scoreNinetyPlus }}</text>
					<text class="summary-label">90分以上</text>
				</view>
				<view class="summary-item">
					<text class="summary-number">{{ scoreStatistics.scoreZeroToNinety }}</text>
					<text class="summary-label">90分下</text>
				</view>
				<view class="summary-item">
					<text class="summary-number">{{ scoreStatistics.ungraded }}</text>
					<text class="summary-label">未批改</text>
				</view>
			</view>
		</view>

		<!-- 错误统计图表 -->
		<view class="chart-section">
			<view class="chart-header">
				<view class="chart-title-wrapper f f-a-c f-j-c">
					<view style="margin-top: -15rpx;" class="chart-title">分数统计</view>
				</view>
			</view>
			<view class="chart-container">
				<eachet :nameList="studentNameList" :list="studentScoreList"></eachet>
			</view>
		</view>

		<!-- 错字统计图表 -->
		<!-- 	<view class="chart-section">
			<view class="chart-header">
				<view class="chart-title-wrapper f f-a-c f-j-c">
					<view style="margin-top: -15rpx;" class="chart-title">错字统计</view>
				</view>
			</view>
			<view class="chart-container">
				<eachet3 :nameList="errorZiNameList" :list="errorZiList"></eachet3>
			</view>
		</view> -->

		<!-- 作业展示模块 -->
		<view class="homework-section">
			<!-- 异常作业 -->
			<view class="homework-category">
				<view class="category-header">
					<view class="category-tag abnormal">异</view>
					<text class="category-title">异常作业</text>
					<text class="category-action">分享</text>
					<image class="share-icon" src="/static/youjiantou.png"></image>
				</view>
				<view class="homework-images">
					<image v-for="(item, index) in abnormalHomework" :key="index" :src="item.thumbnail"
						class="homework-img" @click="viewHomework(item)"></image>
				</view>
			</view>

			<!-- 优秀作业 -->
			<view class="homework-category">
				<view class="category-header">
					<view class="category-tag excellent">优</view>
					<text class="category-title">优秀作业</text>
					<text class="category-action">分享</text>
					<image class="share-icon" src="/static/youjiantou.png"></image>
				</view>
				<view class="homework-images">
					<image v-for="(item, index) in excellentHomework" :key="index" :src="item.thumbnail"
						class="homework-img" @click="viewHomework(item)"></image>
				</view>
			</view>

			<!-- 待提升作业 -->
			<view class="homework-category">
				<view class="category-header">
					<view class="category-tag improve">待</view>
					<text class="category-title">待提升作业</text>
					<text class="category-action">分享</text>
					<image class="share-icon" src="/static/youjiantou.png"></image>
				</view>
				<view class="homework-images">
					<image v-for="(item, index) in improvementHomework" :key="index" :src="item.thumbnail"
						class="homework-img" @click="viewHomework(item)"></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uCharts from "@qiun/ucharts";
	import eachet from "@/components/eachet.vue";
	export default {
		components: {
			eachet,
		},
		data() {
			return {
				// 学生分数统计数据（图表）
				studentScoreList: [], // 分数数组
				studentNameList: [], // 学生姓名数组

				// 原有的模拟数据（作为备用）
				list: [],
				nameList: [],

				// 接口返回的完整数据
				reportData: {},

				// 动态分数统计数据
				scoreStatistics: {
					scoreNinetyPlus: 0, // 90分以上人数
					scoreZeroToNinety: 0, // 0-90分人数
					ungraded: 0, // 未批改人数
				},

				statistics: {
					totalStudents: 20,
					friends: 19,
					trainings: 17,
					abnormal: 2,
					unreviewed: 2,
					unsubmittedStudent: "小红",
					allCorrect: 10,
					hasErrors: 7,
					ungraded: 2,
				},

				// 图表数据
				errorChartData: {
					categories: ["第1题", "第2题", "第3题", "第4题", "第5题"],
					series: [{
							name: "错误A",
							data: [15, 8, 12, 10, 16],
						},
						{
							name: "错误B",
							data: [20, 15, 18, 14, 20],
						},
						{
							name: "错误C",
							data: [12, 18, 15, 16, 12],
						},
						{
							name: "错误D",
							data: [8, 12, 10, 8, 14],
						},
					],
				},

				tutorChartData: {
					categories: ["第1题", "第2题", "第3题", "第4题", "第5题"],
					series: [{
							name: "辅导A",
							data: [15, 8, 12, 10, 16],
						},
						{
							name: "辅导B",
							data: [20, 15, 18, 14, 20],
						},
						{
							name: "辅导C",
							data: [12, 18, 15, 16, 12],
						},
						{
							name: "辅导D",
							data: [8, 12, 10, 8, 14],
						},
					],
				},
				// 作业数据
				abnormalHomework: [],
				excellentHomework: [],
				improvementHomework: [],
			};
		},

		onReady() {
			this.initErrorChart();
			this.initTutorChart();
		},
		onLoad(options) {
			this.init(options.taskId);
		},
		methods: {
			async init(id) {
				try {
					let n = await this.$api.compositionReport({
						taskId: id,
					});

					if (n.code == "0000" && n.data) {
						this.reportData = n.data;
						console.log("接口返回数据:", JSON.stringify(this.reportData));

						// 处理学生分数统计数据
						this.processStudentScoreData();

						// 处理作业图片数据
						await this.processHomeworkImages();

						// 更新统计信息
						this.updateStatistics();
					} else {
						console.error("获取报告数据失败:", n);
						this.setFallbackData();
					}
				} catch (error) {
					console.error("请求报告数据异常:", error);
					this.setFallbackData();
				}
			},

			/**
			 * 处理学生分数统计数据
			 */
			processStudentScoreData() {
				if (!this.reportData.students || this.reportData.students.length == 0) {
					console.log("没有学生数据，使用默认数据");
					this.studentNameList = ["默认学生"];
					this.studentScoreList = [0];
					return;
				}

				// 按分数降序排序，取前7个
				const sortedStudents = this.reportData.students
					.sort((a, b) => (b.score || 0) - (a.score || 0))
					.slice(0, 7);

				this.studentNameList = sortedStudents.map(
					(student) => student.studentName || "未知学生"
				);
				this.studentScoreList = sortedStudents.map(
					(student) => student.score || 0
				);

				console.log("学生分数统计数据处理完成:");
				console.log("学生姓名:", this.studentNameList);
				console.log("学生分数:", this.studentScoreList);

				// 计算分数统计
				this.calculateScoreStatistics();
			},

			/**
			 * 计算分数统计数据
			 */
			calculateScoreStatistics() {
				if (!this.reportData.students || this.reportData.students.length === 0) {
					console.log("没有学生数据，重置统计数据");
					this.scoreStatistics = {
						scoreNinetyPlus: 0,
						scoreZeroToNinety: 0,
						ungraded: 0,
					};
					return;
				}

				let scoreNinetyPlus = 0; // 90分以上
				let scoreZeroToNinety = 0; // 0-90分
				let ungraded = 0; // 未批改

				this.reportData.students.forEach((student) => {
					const score = student.score;

					// 判断是否有分数（已批改）
					if (score === null || score === undefined || score === "") {
						ungraded++;
					} else {
						const numScore = Number(score);
						if (numScore >= 90) {
							scoreNinetyPlus++;
						} else {
							scoreZeroToNinety++;
						}
					}
				});

				this.scoreStatistics = {
					scoreNinetyPlus,
					scoreZeroToNinety,
					ungraded,
				};

				console.log("分数统计计算完成:", this.scoreStatistics);
				console.log(
					`90分以上: ${scoreNinetyPlus}人, 0-90分: ${scoreZeroToNinety}人, 未批改: ${ungraded}人`
				);
			},

			/**
			 * 更新统计信息
			 */
			updateStatistics() {
				if (this.reportData) {
					this.statistics = {
						...this.statistics,
						totalStudents: this.reportData.classStuNum || 0,
						submitted: this.reportData.submitNum || 0,
						checked: this.reportData.checkNum || 0,
						abnormal: this.reportData.exceptNum || 0,
						scoreNinetyNum: this.reportData.scoreNinetyNum || 0,
						scoreZeroNineNum: this.reportData.scoreZeroNineNum || 0,
						averageScore: this.reportData.averageScore || 0,
					};
				}
			},

			/**
			 * 设置备用数据
			 */
			setFallbackData() {
				console.log("使用备用数据");
				this.studentNameList = ["学生A", "学生B", "学生C"];
				this.studentScoreList = [85, 78, 92];

				// 设置备用统计数据
				this.scoreStatistics = {
					scoreNinetyPlus: 1, // 学生C: 92分
					scoreZeroToNinety: 2, // 学生A: 85分, 学生B: 78分
					ungraded: 0,
				};
			},

			/**
			 * 处理作业图片数据
			 */
			async processHomeworkImages() {
				console.log("开始处理作业图片数据...");

				try {
					// 并行处理三种类型的作业图片
					const [abnormalHomework, excellentHomework, improvementHomework] =
					await Promise.all([
						this.fetchHomeworkImages(
							this.reportData.exceptHomeworks || [],
							"abnormal"
						),
						this.fetchHomeworkImages(
							this.reportData.excellentHomeworks || [],
							"excellent"
						),
						this.fetchHomeworkImages(
							this.reportData.needImproveHomeworks || [],
							"improvement"
						),
					]);

					this.abnormalHomework = abnormalHomework;
					this.excellentHomework = excellentHomework;
					this.improvementHomework = improvementHomework;

					console.log("作业图片处理完成:");
					console.log("异常作业:", this.abnormalHomework);
					console.log("优秀作业:", this.excellentHomework);
					console.log("需要提升作业:", this.improvementHomework);
				} catch (error) {
					console.error("处理作业图片失败:", error);
				}
			},

			/**
			 * 获取作业图片URLs
			 */
			async fetchHomeworkImages(imagePaths, type) {
				if (!imagePaths || imagePaths.length === 0) {
					console.log(`${type} 类型作业无图片数据`);
					return [];
				}

				const homeworkList = [];

				for (let i = 0; i < imagePaths.length; i++) {
					const imagePath = imagePaths[i];
					try {
						console.log(`正在获取 ${type} 作业图片 ${i + 1}:`, imagePath);

						const imageResponse = await this.$api.imageUrl({
							image: imagePath,
						});

						if (imageResponse.code === "0000" && imageResponse.data) {
							homeworkList.push({
								id: `${type}_${i + 1}`,
								thumbnail: imageResponse.data,
								imagePath: imagePath,
								type: type,
								index: i,
							});
							console.log(
								`${type} 作业图片 ${i + 1} 获取成功:`,
								imageResponse.data
							);
						} else {
							console.error(`${type} 作业图片 ${i + 1} 获取失败:`, imageResponse);
						}
					} catch (error) {
						console.error(`${type} 作业图片 ${i + 1} 请求异常:`, error);
					}
				}

				return homeworkList;
			},

			// 初始化错误统计图表
			initErrorChart() {
				this.list = [4, 5, 8, 10, 2, 5, 7];
				this.nameList = ["lzl", "lll", "llz", "zll", "zzl", "xz", "zx"];
				this.errorChart = new uCharts({
					type: "column",
					context: uni.createCanvasContext("errorChart", this),
					width: uni.upx2px(690),
					height: uni.upx2px(400),
					categories: this.errorChartData.categories,
					series: this.errorChartData.series,
					animation: true,
					background: "#FFFFFF",
					color: ["#5470C6", "#91CC75", "#FAC858", "#EE6666"],
					padding: [15, 15, 0, 5],
					enableScroll: false,
					legend: {
						show: false,
					},
					xAxis: {
						disableGrid: true,
						itemCount: 5,
						scrollShow: true,
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
						data: [{
							min: 0,
							max: 25,
						}, ],
					},
					extra: {
						column: {
							type: "group",
							width: uni.upx2px(20),
							activeBgColor: "#000000",
							activeBgOpacity: 0.08,
						},
					},
				});
			},

			// 初始化辅导统计图表
			initTutorChart() {
				this.tutorChart = new uCharts({
					type: "column",
					context: uni.createCanvasContext("tutorChart", this),
					width: uni.upx2px(690),
					height: uni.upx2px(400),
					categories: this.tutorChartData.categories,
					series: this.tutorChartData.series,
					animation: true,
					background: "#FFFFFF",
					color: ["#5470C6", "#91CC75", "#FAC858", "#EE6666"],
					padding: [15, 15, 0, 5],
					enableScroll: false,
					legend: {
						show: false,
					},
					xAxis: {
						disableGrid: true,
						itemCount: 5,
						scrollShow: true,
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
						data: [{
							min: 0,
							max: 25,
						}, ],
					},
					extra: {
						column: {
							type: "group",
							width: uni.upx2px(20),
							activeBgColor: "#000000",
							activeBgOpacity: 0.08,
						},
					},
				});
			},

			// 图表触摸事件
			touchErrorChart(e) {
				this.errorChart.showToolTip(e, {
					format: function(item, category) {
						return category + " " + item.name + ":" + item.data;
					},
				});
			},

			moveErrorChart(e) {
				this.errorChart.scroll(e);
			},

			touchEndErrorChart(e) {
				this.errorChart.hideToolTip();
			},

			touchTutorChart(e) {
				this.tutorChart.showToolTip(e, {
					format: function(item, category) {
						return category + " " + item.name + ":" + item.data;
					},
				});
			},

			moveTutorChart(e) {
				this.tutorChart.scroll(e);
			},

			touchEndTutorChart(e) {
				this.tutorChart.hideToolTip();
			},

			// 查看具体作业
			viewHomework(homework) {
				console.log("查看作业详情:", homework);

				// 预览图片
				uni.previewImage({
					urls: [homework.thumbnail],
					current: homework.thumbnail,
					success: () => {
						console.log("图片预览成功");
					},
					fail: (error) => {
						console.error("图片预览失败:", error);
						uni.showToast({
							title: "图片预览失败",
							icon: "error",
						});
					},
				});
			},

			handleImageError(e) {
				console.error("图片加载失败:", e);
				uni.showToast({
					title: "图片加载失败",
					icon: "error",
				});
			},

			handleImageLoad(e) {
				console.log("图片加载成功:", e);
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: linear-gradient(180deg, #05C490 0%, #5CDFA9 33%, #8EF3BF 66%, #ECF2F0 100%);
	}

	// 顶部渐变背景区域
	.header-section {
		padding: 30rpx;
		padding-bottom: 0;
	}

	// 听写报告模块
	.report-header {

		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 30rpx;

		.report-left {
			flex: 1;
			position: relative;
			z-index: 10;
			margin-right: 30rpx;

			.report-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
			}

			.report-desc {
				font-size: 28rpx;
				color: #666;
				line-height: 1.5;
				margin-bottom: 10rpx;
			}
		}

		.report-right {
			display: flex;
			flex-direction: column;
			align-items: center;

			.task-detail {
				font-size: 28rpx;
				color: #fff;
				margin-bottom: 20rpx;
				text-align: right;
			}

			.ai-bg {
				position: relative;
				display: flex;
				flex-direction: column;
				align-items: center;

				.ai-icon {
					position: absolute;
					z-index: 1;
					width: 270rpx;
					height: 234rpx;
					top: -40rpx;
					right: -80rpx;
				}

				.ai-text {
					font-size: 24rpx;
					color: #333;
					margin-top: 10rpx;
				}
			}
		}
	}

	// 数据统计模块
	.stats-section {
		position: relative;
		z-index: 10;
		margin: 30rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

		.stats-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;
			margin-bottom: 40rpx;

			.stat-item {
				padding: 20rpx;
				background: linear-gradient(309deg, #E6FAFE 0%, #D1FFEB 100%);
				border-radius: 12rpx;
				text-align: center;

				.stat-label {
					font-size: 28rpx;
					color: #007D5B;
					font-weight: 500;
				}
			}
		}

		.summary-stats {
			display: flex;
			justify-content: space-around;
			align-items: center;

			.summary-item {
				display: flex;
				flex-direction: column;
				align-items: center;

				.summary-number {
					font-size: 48rpx;
					font-weight: bold;
					color: #007D5B;
					margin-bottom: 10rpx;
				}

				.summary-label {
					font-size: 28rpx;
					color: #007D5B;
				}
			}
		}
	}

	// 图表区域
	.chart-section {
		margin: 30rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

		.chart-header {
			display: flex;
			justify-content: flex-start;
			margin-bottom: 20rpx;

			.chart-title-wrapper {
				width: 200rpx;
				height: 67rpx;
				position: relative;
				top: -40rpx;
				left: -50rpx;
				display: flex;
				align-items: center;
				background: url('/static/chatTitle.png') no-repeat center center;
				background-size: 100% 100%;


				.chart-title {
					font-size: 28rpx;
					color: white;
					font-weight: 500;
					text-align: center;
				}
			}
		}

		.chart-container {
			width: 100%;
			height: 400rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			.charts {
				width: 690rpx;
				height: 400rpx;
			}
		}
	}

	/* 作业展示模块样式 */
	.homework-section {
		margin: 30rpx;
		margin-top: 0;
	}

	.homework-category {
		background: white;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.category-header {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.category-tag {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 28rpx;
		font-weight: bold;
		margin-right: 20rpx;
	}

	.category-tag.abnormal {
		background: #FF6B35;
	}

	.category-tag.excellent {
		background: #FFD700;
	}

	.category-tag.improve {
		background: #999;
	}

	.category-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		flex: 1;
	}

	.category-action {
		font-size: 28rpx;
		color: #666;
		margin-right: 10rpx;
	}

	.share-icon {
		width: 24rpx;
		height: 24rpx;
	}

	.homework-images {
		display: flex;
		gap: 20rpx;
	}

	.homework-img {
		width: 200rpx;
		height: 280rpx;
		border-radius: 12rpx;
		border: 2rpx solid #eee;
	}
</style>